import { Component } from 'react';
import Taro, { getCurrentInstance } from '@tarojs/taro';
import { View, Text, ScrollView, Image } from '@tarojs/components'
import classNames from 'classnames'
import Iconfont from '@/components/Iconfont'
import './index.scss'
import Skeleton from 'taro-skeleton'
import { formatToAsterisk } from '@/utils'
import { fetchDetail } from '@/api/detection'
type State = {
	all: any
	base: any
	focus: Array<any>
	countAll: number
	countFocus: number
	loading: boolean
};
export default class Detail extends Component<{}, State> {
    $instance = getCurrentInstance();


    constructor(props) {
		super(props)
		this.state = {
			all: [],
			base: [],
			focus: [],
			countAll: 0,
			countFocus: 0,
			loading: true
		}
	}

    getClassNameByRange(range: number, type: number = 1): string {
		let bgcClassNames: string[] = ['bgc-red', 'bgc-yellow-shallow', 'bgc-yellow-deep', 'bgc-green']
		let colorClassNames: string[] = ['color-red', 'color-yellow-shallow', 'color-yellow-deep', 'color-green']
		let bgcClassName: string = ''
		let colorClassName: string = ''
		if (range < 0 || range > 100) {
			console.error('范围值不对')
		}
		if (0 <= range && range <= 59) {
			bgcClassName = bgcClassNames[0]
			colorClassName = colorClassNames[0]
		} else if (60 <= range && range <= 79) {
			bgcClassName = bgcClassNames[1]
			colorClassName = colorClassNames[1]
		} else if (80 <= range && range <= 99) {
			bgcClassName = bgcClassNames[2]
			colorClassName = colorClassNames[2]
		} else if (range === 100) {
			bgcClassName = bgcClassNames[3]
			colorClassName = colorClassNames[3]
		} else {
			bgcClassName = ''
			colorClassName = ''
		}
		return type === 1 ? bgcClassName : colorClassName

	}

    handCilck(index: number) {
		const array = [...this.state.all]
		array[index] = { ...array[index], show: !this.state.all[index].show }
		this.setState({
			all: array
		})
	}

    async getRecordDetail() {
		const { reportId } = this.$instance.router.params
		try {
			let res: any = await fetchDetail(reportId)
			let data = res.data.data
			console.log('data', data)
			let { all, base, focus, countAll, countFocus } = data
			all = data.all.map(item => {
				return {
					...item,
					show: true
				}
			})
			this.setState({
				all,
				base,
				focus,
				countAll,
				countFocus
			})
		} catch (error) {
			console.log(error)
		} finally {
			this.setState({
				loading: false
			})
		}
	}

    previewImgs(current: string, urls: Array<any>) {
		urls = urls.map(url => url.img)
		console.log(current, urls)
		Taro.previewImage({
			current,
			urls
		})
	}

    setTitle() {
		const { params } = this.$instance.router
		Taro.setNavigationBarTitle({
			title: params.title || '详情'
		})
	}

    UNSAFE_componentWillMount() {
		this.setTitle()
		this.getRecordDetail()
	}
    componentDidMount() {

	}

    render() {
		const { base, all, focus, countAll, countFocus, loading } = this.state
		console.log(all)
		let baseCarInfoView = <Skeleton title avatar avatarShape={'square'} row={1} rowHeight={36} loading={loading}>
			<View className='car-info'>
				<View className='car-info-brand-logo'>
					<Image lazyLoad={true} mode='aspectFit' src={base.logo}></Image>
				</View>
				<View className='car-info-detail'>
					<View className='brand-name'>{base.carSeries}</View>
					<View className='series-model'>{base.carModel}</View>
				</View>
			</View>
		</Skeleton>

		let detectionStateClassName = this.getClassNameByRange(base.fraction)
		let detectionStateColorClassName = this.getClassNameByRange(base.fraction, 2)
		let formarVin = formatToAsterisk(String(base.vin))
		let baseDetectionInfoView = <Skeleton row={4} rowHeight={[28, 28, 28, 100]} loading={loading}>
			<View className='detection-info'>
				<View className='top'>
					<View className='row-item'>
						<View className='label'>车牌号码：</View>
						<View className='val'>{base.carLicense}</View>
					</View>
					<View className='row-item'>
						<View className='label'>车架号：</View>
						<View className='val'>{formarVin}</View>
					</View>
					<View className='row-item'>
						<View className='label'>公里数：</View>
						<View className='val'>{base.currentMile}km</View>
					</View>
				</View>
				<View className={
					classNames('bottom', detectionStateClassName)
				}>
					<View className='score-wrap'>
						<View className={
							classNames('score', detectionStateColorClassName)
						}>{base.fraction}</View>
						<View className='score-text'>综合评分</View>
					</View>
					<View className='detecter-wrap'>
						<View className='detecter'>{base.inspector}</View>
						<View className='score-text'>{base.checkedAt}</View>
					</View>
				</View>
			</View>
		</Skeleton>

		let foucsView = focus.map((item, index) => {
			return <View className='attention-content-item' key={item.checkItemId}>
				<View className='attention-content-item-title'>
					<View className='left'>
						<View className="name">{index + 1}、{item.checkItemName}
							<View className={
								classNames('tag', {
									'color-border-green': item.attention === 0,
									'color-border-yellow-deep': item.attention === 1,
									'color-border-yellow-shallow': item.attention === 2,
									'color-border-red': item.attention === 3
								})
							}>{item.attentionDegree}</View>
						</View>
					</View>
					<View className='right'>
						<Iconfont size="44" color="#F40000" name="icon-buliang1" />
					</View>
				</View>
				{item.checkResultList.length > 0 &&
					<View className='attention-content-item-result'>
						<View className='title'>检测结果：</View>
						<View className='content'>
							<View className='content-item'>
								{item.checkResultList.map((result, resultIndx) =>
									<View key={resultIndx}>
										{item.checkResultList.length > 1 && <Text className='order'>{resultIndx + 1}</Text>}
										{result}
									</View>
								)}
							</View>
						</View>
					</View>
				}
				{item.diagnosisResultList.length > 0 &&
					<View className='attention-content-item-result-2'>
						<View className='title'>诊断结果：</View>
						<View className='content'>
							<View className='content-item-text'>
								{item.diagnosisResultList.map((dnResult, dnResultIndx) =>
									<View key={dnResultIndx}>
										{item.diagnosisResultList.length > 1 && <Text className='order'>{dnResultIndx + 1}</Text>}
										{dnResult}
									</View>
								)}
							</View>
						</View>
					</View>
				}
				{item.images.length > 0 ?
					<View className='attention-content-item-imgs'>
						{item.images.map(url =>
							<Image key={url.img} lazyLoad={true} onClick={this.previewImgs.bind(this, url, item.images)} mode='aspectFill' src={url.img}></Image>
						)}
					</View>
					:null
				}
			</View>
		})

		let allView = all.map((item, index) => {
			return <View className='all-content-item-wrap' key={item.categoryId}>
				<View className="all-content-item-wrap-title" onClick={this.handCilck.bind(this, index)}>
					<View className='all-content-item-wrap-title-left'>
						<Text className="tip">
							{item.categoryName}（{item.countItems}项）
						</Text>
					</View>
					<View className='all-content-item-wrap-title-right'>
						{item.focusCount > 0 &&
							<Text className="tip">
								{item.focusCount}个关注项
							</Text>
						}
						<View className="action">

							{item.show ?
								<Text className='action-text'>收起</Text> :
								<Text className='action-text'>展开</Text>
							}
							<Iconfont size="44" activeClassName={classNames({ 'active': item.show })} color="#666666" name="icon-shouqi" />
						</View>
					</View>
				</View>
				{item.items.map((result, resultIndx) =>
					<View key={result.checkItemId} className={classNames('all-content-item no-border-radius', {
						'visiable': item.show,
						'hidden': !item.show
					})}>
						<View className='all-content-item-title'>
							<View className='left'>
								<View className="name">{resultIndx + 1}、{result.itemName}
									{result.status !== 1 &&
										<View className={
											classNames('tag', {
												'color-border-green': result.attention === 0,
												'color-border-yellow-deep': result.attention === 1,
												'color-border-yellow-shallow': result.attention === 2,
												'color-border-red': result.attention === 3
											})
										}>{result.attentionDegree}</View>
									}
								</View>
							</View>
							<View className='right'>
								{result.status == 0 ? <Iconfont size="44" color="#F40000" name="icon-buliang1" /> : ''}
								{result.status == 1 ? <Iconfont size="44" color="#3CC504" name="icon-zhengchang" /> : ''}
								{result.status === 3 ? '未检测' : ''}
							</View>
						</View>
						{result.checkResultList.length > 0 &&
							<View className='all-content-item-result'>
								<View className='title'>检测结果：</View>
								<View className='content'>
									<View className='content-item'>
										{result.checkResultList.map((check, checkIndx) =>
											<View key={checkIndx}>
												{result.checkResultList.length > 1 && <Text className='order'>{checkIndx + 1}</Text>}
												{check}
											</View>
										)}
									</View>
								</View>
							</View>
						}
						{result.diagnosisResultList.length > 0 &&
							<View className='all-content-item-result-2'>
								<View className='title'>诊断结果：</View>
								<View className='content'>
									<View className='content-item-text'>
										{result.diagnosisResultList.map((dnResult, dnResultIndx) =>
											<View key={dnResultIndx}>
												{result.diagnosisResultList.length > 1 && <Text className='order'>{dnResultIndx + 1}</Text>}
												{dnResult}
											</View>
										)}
									</View>
								</View>
							</View>
						}
						{result.images.length > 0 &&
							<View className='all-content-item-imgs'>
								{result.images.map(url =>
									<Image key={url.img} onClick={this.previewImgs.bind(this, url.img, result.images)} lazyLoad={true} mode='aspectFill' src={url.img}></Image>
								)}
							</View>
						}
					</View>
				)}
			</View>
		})

		const scrollStyle = {
			height: '100vh'
		}

		return (
			<View className="record-detail">
				<ScrollView className='list' enableBackToTop={true} scrollY={true} style={scrollStyle}>
					{baseCarInfoView}
					{baseDetectionInfoView}
					<Skeleton title row={1} rowHeight={500} loading={loading}>
						<View className='content'>
							{countFocus ? <View className='attention'>
								<View className='attention-title'>共<View className='attention-title-active'>{countFocus}</View>个关注项</View>
								<View className='attention-content'>
									{foucsView}
								</View>
							</View> : null
							}
							<View className='all'>
								<View className='all-title'>全部检测项</View>
								<View className='all-content'>
									{allView}
								</View>
							</View>
						</View>
					</Skeleton>
				</ScrollView>
			</View>
		)
	}
}
